//MultitonKeyGenerator.java
package singletonAndMultiton;
import java.util.HashMap;
/**
 * @author:youtubezou
 * @version:2012-7-14
 */
public class MultitonKeyGenerator {
	/* Note: there are multiple MultitonKeyGenerator objects exist */
	private static HashMap<String, MultitonKeyGenerator> keyGens = 
								new HashMap<String, MultitonKeyGenerator>(10);
	
	private static  final int POOL_SIZE = 20;
	
	private KeyInfo keyInfo;
	
	private MultitonKeyGenerator(String name) {
		keyInfo = new KeyInfo(POOL_SIZE, name);
	}
	
	public static synchronized MultitonKeyGenerator getInstance(String name){
		if (!keyGens.containsKey(name))	/*record*/
			keyGens.put(name, new MultitonKeyGenerator(name));
		return keyGens.get(name);
	}
	
	public synchronized int getNextKey(){
		return keyInfo.getNextKey();
	}
	
	

	public static void main(String[] args) {
		MultitonKeyGenerator mulKeyGen = MultitonKeyGenerator.getInstance("US");
		
		System.out.println("MultitonKeyGenerator Test");
		for (int i = 0; i < 30; i++)
			System.out.println(mulKeyGen.getNextKey());

	}

}
